<?php

class AuctionAction extends CommonAction {
	private $prize_type = 'auction';
	private $_description = array ('1' => '出价成功', '-1' => '拍卖未开始', '-2' => '拍卖已结束', '-3' => '已经拍了一个商品', '-4' => '金币不够', '-5' => '数据库错误');
	
	
	
	public function _getByPeriod($period){
		$_au['au_periods'] = $period;
		$join = ' left join ws_prize_store on ws_prize_store.prst_id=ws_prize_auction.prst_id 
				  left join ws_user on ws_user.u_id=ws_prize_auction.u_id ';
		$list = M('PrizeAuction')->where($_au)->join($join)->select();
		return $list;
	}
	
	
	
	# 出价
	public function onOffer() {
		$au_id = $_REQUEST['au_id'];
		$user = getInfoById ( 'User', $this->Core->User->u_id );
		$auction = getInfoById ( 'PrizeAuction', $au_id );
		
		$_result = $this->checkTime ( $auction );
		
		if ($_result == 1)
			$_result = $this->checkAuctionLock ( $user );
		
		if ($_result == 1)
			$_result = $this->checkEnough ( $user, $auction );
		
		if ($_result == 1)
			$_result = $this->onAuction ( $user, $auction );
		
		$_rdata = array ('status' => $_result, 'msg' => $this->_description [$_result] );
		die ( json_encode ( $_rdata ) );
	}
	
	# 检查是否在拍卖时间段内
	private function checkTime($auction) {
		if (time () < $auction ['au_stime']) {
			return - 1;
		} elseif (time () > $auction ['au_etime']) {
			return - 2;
		} else {
			return 1;
		}
	}
	
	# 检查是否被锁住（即当前用户已经拍卖了一个产品）
	private function checkAuctionLock($user) {
		return ($user ['u_lock_auid']>0) ? - 3 : 1;
	}
	
	# 检查用户金币是否足够
	private function checkEnough($user, $auction) {
		return $user ['u_golds'] < ($auction ['au_golds'] + $auction ['au_single_golds']) ? - 4 : 1;
	}
	
	# 开始竞价
	private function onAuction($user, $auction) {
		# step.1 取消产品用户锁
		if ($auction ['u_id'])
			D ( 'User' )->auctionUnLock ( $auction ['u_id'] );
		
		# step.2 建立新锁
		D ( 'User' )->auctionLock ( $user ['u_id'], $auction ['au_id'] );
		
		# step.3 更新拍卖价格和所属用户
		D ( 'Auction' )->onAuction ( $user, $auction );
		return 1;
	}

}
?>